use axum::Json;
use serde_json::Value;
use crate::{reqwest, query, code, rdb };
use redis::{Commands, RedisError, Connection};
// 生成 access_token
async fn create_access_token(corpid:&str, secret:&str, conn:&mut Connection )-> Result<String, Json<Value>>{
    let url = format!(
        "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={}",
        corpid, secret
    );
    let rs = &mut reqwest::get(&url).await?;
    let key = corpid.to_string() + "_access_token";

    if let Some(f) = query::str_op(rs, "access_token")? {
        let expire = query::i64(rs, "expires_in")?;
        let _:() = conn.set(&key, &f).unwrap();
        let _:() = conn.expire(key, expire).unwrap();
        Ok(f)
    }else {
        Err(code::err_("access_token 获取失败"))
    }
}
// 获取 access_token
pub async fn token(corpid:&str, secret:&str) -> Result<String, Json<Value>>{
    let conn = &mut rdb::connect("1")?;
    let key = corpid.to_string() + "_access_token";
    let token: Result<String, RedisError> = conn.get(&key);
    match token {
        Ok(f) => Ok(f),
        Err(_e) => Ok(create_access_token(corpid, secret, conn).await?)
    }
}